import React, { Component } from 'react';
import {
  StyleSheet, Text, View, Image, TouchableOpacity, Modal,
  ScrollView, PixelRatio, KeyboardAvoidingView, Platform, Keyboard, Switch, FlatList
} from "react-native";
import { style } from '../../../theme/style';
import { GLOBAL } from '../../../config/global';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { Common } from '../../../component/common/Common.js';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
import { RangTime } from '../../../component/common/RangTime.js';
import moment from 'moment';
import Permission from '../../../utils/permission';
import { NavigationEvents } from 'react-navigation';

const scale = GLOBAL.SCALE;
const arrowIcon = require('../../../imgs/select.png');
const STATUS_LIST = [
  {
    title: '全部',
    dickKey: ''
  }, {
    title: '草稿',
    dickKey: 'RPT_DRAFT'
  }, {
    title: '审批中',
    dickList: 'RPT_AUDITING'
  }, {
    title: '审批驳回',
    dickKey: 'RPT_AUDIT_UNPASS'
  }, {
    title: '审批通过',
    dickKey: 'EXECUTING'
  }, {
    title: '撤回审批中',
    dickKey: 'EXECUTING'
  }, {
    title: '已撤销',
    dickKey: 'EXECUTING'
  }
];
const STATUS_FILTER = ['RPT_AUDITING', 'RPT_AUDIT_UNPASS', 'RPT_ADUIT_PASS', 'EXECUTING', 'RPT_DRAFT', 'RPT_CANCELING', 'RPT_CANCEL']

export class SinoNewOilQueryListPage extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      headerTitle: '中新油美金成交查询列表',
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack(); }} color='#fff' />,
      headerTintColor: style.color.white,
      headerStyle: style.head.headerStyle,
    }
  };

  constructor(props) {
    super(props);
    this.state = {
      status: 'data',
      orderType: 'P',
      showSelect: false,
      selectIndex: 0,
      statusKey: '',
      statusText: '全部',
      showTimeModal: false,
      refreshIcon: false, // 下拉刷新图标
      listData: []
    }
    this.onRefresh = true; // 判断是整个页面刷新还是下拉刷新
    this.totalPage = 1;
    this.orderTypeList = [
      {
        orderType: 'P',
        value: '采购成交',
        count: '',
        permission: 'ZXY005',
      },
      {
        orderType: 'S',
        value: '销售成交',
        count: '',
        permission: 'ZXY006',
      },
      {
        orderType: '',
        value: '闭口成交',
        count: '',
        permission: 'ZXY007',
      }
    ];
    this.pageParams = {
      pageNo: 1,
      pageSize: 10,
      orderType: 'P', // S-销售 P-采购
      bizMode: 0, // 闭口需要传1
      statusList: STATUS_FILTER,
      beginDate: '',
      endDate: '',
    }
  }

  async componentWillMount() {
    let { orderType, bizMode } = this.props.navigation.state.params;
    if (orderType) {
      this.setState({
        orderType,
      })
      this.pageParams.orderType = orderType;
      this.pageParams.bizMode = 0;
    } else if (bizMode) {
      this.setState({
        orderType: ''
      })
      this.pageParams.orderType = 'S';
      this.pageParams.bizMode = bizMode;
    }
    await this.getOrderRecord();
    this.initPage();
  }

  initPage = async () => {
    this.setState({
      status: this.onRefresh ? 'loading' : 'data',
      refreshIcon: !this.onRefresh && this.pageParams.pageNo == '1'
    })
    let res = await HTTP.POST(API_GENERATE(API.GET_NEW_OIL_ORDER_LIST), this.pageParams);
    if (res) {
      this.totalPage = res.totalPage;
      this.setState({
        status: res.rows.length > 0 ? 'data' : 'empty',
        listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
        refreshIcon: false
      })
    } else {
      this.setState({
        refreshIcon: false,
        status: 'error'
      })
    }
  }

  getOrderRecord = async () => {
    let res = await HTTP.POST(API_GENERATE(API.GET_NEW_OIL_ORDER_RECORD), this.pageParams);
    if (res) {
      this.orderTypeList[0].count = res.purchaseOrders;
      this.orderTypeList[1].count = res.saleOrders;
      this.orderTypeList[2].count = res.oppoOrders;
      this.setState({ ls: true })
    }
  }

  // 切换tab
  changeTab = (orderType, value) => {
    // 采购和销售需要传orderType, 闭口需传bizMode=1
    if (orderType) {
      this.pageParams.orderType = orderType;
      this.pageParams.bizMode = 0;
    } else {
      this.pageParams.orderType = 'S';
      this.pageParams.bizMode = 1;
    }
    this.setState({
      orderType,
    }, () => {
      // this.refresh();
      this.pageParams.pageNo = 1;
      this.onRefresh = true;
      this.initPage();
    })
  }

  // 日期过滤
  _resultCall = (resultData) => {
    this.pageParams.beginDate = resultData.startTime ? moment(new Date(resultData.startTime)).format('YYYY/MM/DD') : '';
    this.pageParams.endDate = resultData.endTime ? moment(new Date(resultData.endTime)).format('YYYY/MM/DD') : '';
    this.setState({
      showTimeModal: false
    }, () => {
      this.refresh()
    })
  }

  // 下拉刷新
  refresh = () => {
    this.pageParams.pageNo = 1;
    this.onRefresh = false;
    this.getOrderRecord()
    this.initPage();
  }

  // 加载更多
  loadMore = () => {
    if (this.totalPage > this.pageParams.pageNo) {
      this.pageParams.pageNo++;
      this.onRefresh = false;
      this.initPage();
    }
  }

  onErrorRefresh = () => {
    this.pageParams.pageNo = 1;
    this.onRefresh = true;
    this.getOrderRecord()
    this.initPage();
  }

  // 切换状态
  changeStatus = (res) => {
    if (res) {
      this.pageParams.statusList = [];
      if (res.item.dickKey) {
        this.pageParams.statusList.push(res.item.dickKey);
      } else if (res.item.dickList) {
        this.pageParams.statusList = res.item.dickList
      } else {
        this.pageParams.statusList = STATUS_FILTER;
      }
      this.setState({
        showSelect: false,
        selectIndex: res.index,
        statusKey: res.item.dickKey,
        statusText: res.item.title,
      }, () => {
        this.refresh();
      })
    }
  }

  jumpPage = (status, orderId, statusName) => {
    let goPage = '';
    let params = {
      paramsData: {
        orderId,
        orderType: this.pageParams.orderType,
        bizMode: this.pageParams.bizMode,
        status,
        statusName,
      }
    }
    if (status == 'RPT_DRAFT' || status == 'RPT_AUDIT_UNPASS') {
      goPage = 'SinoNewOrderBaseInfoPage'
    } else {
      goPage = 'SinoNewOrderDetailPage'
    }
    this.props.navigation.navigate(goPage, params)
  }



  renderTabWap = () => {
    let { orderType } = this.state;
    return (
      <View style={styles.tabWrap}>
        {
          this.orderTypeList && this.orderTypeList.length > 0 ? (
            this.orderTypeList.map((item, index) => {
              return (
                Permission.check(item.permission) ? (<TouchableOpacity key={index} style={styles.tabItem} onPress={() => { this.changeTab(item.orderType, item.value) }}>
                  <Text style={[styles.tabValue, orderType == item.orderType ? styles.selectedValue : '']}>{item.value}</Text>
                  <Text style={[styles.tabCount, orderType == item.orderType ? styles.selectedCount : '']}>{item.count}</Text>
                </TouchableOpacity>) : null
              )
            })
          ) : null
        }
      </View>
    )
  }

  renderFilterWrap = () => {
    let { beginDate, endDate } = this.pageParams;
    let { statusText } = this.state;
    return (
      <View style={styles.filterWrap}>
        <TouchableOpacity style={styles.statusWrap} onPress={() => {
          this.setState({
            showSelect: !this.state.showSelect
          })
        }}>
          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
            <Text style={styles.statusBtn}>{statusText}</Text>
            <Image source={arrowIcon} style={styles.arrowIcon} />
          </View>
        </TouchableOpacity>

        <TouchableOpacity style={styles.statusWrap} onPress={() => {
          this.setState({
            showTimeModal: !this.state.showTimeModal,
            showSelect: false,
          })
        }}>
          <Text>{beginDate || '开始时间'}-{endDate || '结束时间'}</Text>
        </TouchableOpacity>
      </View>
    )
  }

  renderListItem = (item) => {
    let { orderType } = this.state;
    item = item.item;
    return (
      <TouchableOpacity style={styles.listItem} onPress={() => { this.jumpPage(item.status, item.orderId, item.statusName) }}>
        <View style={styles.itemHeader}>
          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
            <Text style={{ fontSize: 12 * scale, color: '#000', marginLeft: 14 * scale }}>{item.orderId || '--'}</Text>
            {/* 撤销中显示‘撤’的标识 */}
            {
              item.status && item.status == 'RPT_CANCELING' ? (
                <View style={styles.backoutIcon}>
                  <Text style={{ color: '#fff', fontSize: 11 * scale }}>撤</Text>
                </View>
              ) : null
            }
          </View>
          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
            <Text style={{ fontSize: 12 * scale, color: '#848A96' }}>{item.createTime || '--'}</Text>
            <Text style={{ fontSize: 12 * scale, color: '#000', marginLeft: 10 * scale, marginRight: 10 * scale }}>{item.statusName || '--'}</Text>
          </View>
        </View>

        <View style={styles.itemBody}>
          {item.zxyOrderItemList.map((item, index) => {
            return (
              <View key={index} style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 17 * scale }}>
                <Text style={{ flex: 1, fontSize: 14 * scale, textAlign: 'left' }} numberOfLines={1}>{item.goodsName || '--'}</Text>
                <Text style={{ flex: 1, fontSize: 14 * scale, textAlign: 'center' }} numberOfLines={1}>{item.quantity || '--'}吨</Text>
                {
                  orderType ? (<Text style={{ flex: 1, fontSize: 14 * scale, textAlign: 'right' }} numberOfLines={1}>{item.nakedPrice || '--'}美元/吨</Text>) :
                    (<View style={{ flex: 1 }}>
                      <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 8 * scale }}>
                        <View style={[styles.tagIcon, { backgroundColor: '#82CD4B' }]}>
                          <Text style={{ color: '#fff', fontSize: 13 * scale, fontWeight: 'bold' }}>采</Text>
                        </View>
                        <View style={{ paddingLeft: 30 * scale }}>
                          <Text numberOfLines={1}>{item.nakedPrice || '--'}美元/吨</Text>
                        </View>
                      </View>

                      <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                        <View style={[styles.tagIcon, { backgroundColor: '#F5A623' }]}>
                          <Text style={{ color: '#fff', fontSize: 13 * scale, fontWeight: 'bold' }}>销</Text>
                        </View>
                        <View style={{ paddingLeft: 30 * scale }}>
                          <Text numberOfLines={1}>{item.nakedSalePrice || '--'}美元/吨</Text>
                        </View>
                      </View>
                    </View>)
                }
              </View>
            )
          })}
        </View>

        <View style={styles.itemFooter}>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 * scale }}>
            <Text style={{ fontSize: 12 * scale, color: '#848A96', flex: 1 }} numberOfLines={1}>{item.companyName || ''}</Text>
            <Text style={{ flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center', flex: 1, textAlign: 'right' }} numberOfLines={1}>
              <Text style={{ fontSize: 12 * scale }}>共 </Text>
              <Text style={{ flex: 3 }}>{item.totalItemQuantity || '--'}</Text>
              <Text style={{ fontSize: 12 * scale }}> 吨</Text>
            </Text>
          </View>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
            <Text style={{ fontSize: 12 * scale, color: '#848A96', flex: 1 }} numberOfLines={1}>{item.bizStaffName || '--'}/{item.organName || '--'}</Text>
            <Text style={{ flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center', flex: 1, textAlign: 'right' }} numberOfLines={1}>
              <Text style={{ fontSize: 12 * scale }}>合计 </Text>
              <Text style={{ fontSize: 17 * scale }}>${item.totalOrderAmt || '--'}</Text>
            </Text>
          </View>
        </View>
      </TouchableOpacity>
    )
  }

  onWillFocus = async () => {
    this.pageParams.pageNo = 1;
    this.onRefresh = false;
    this.getOrderRecord();
    this.initPage();
  }

  render() {
    let { status, listData, refreshIcon, showSelect, selectIndex, showTimeModal } = this.state;
    return (
      <View style={styles.container}>
        <NavigationEvents onWillFocus={() => { this.onWillFocus() }} />

        {this.renderTabWap()}
        {this.renderFilterWrap()}

        {
          status == 'data' ? (<View style={styles.listWrap}>
            <FlatList
              data={listData}
              renderItem={this.renderListItem}
              refreshing={refreshIcon}
              onRefresh={() => { this.refresh() }}
              onEndReachedThreshold={0.1}
              onEndReached={() => { this.loadMore() }}
            />
          </View>) : null
        }

        {
          showTimeModal ? <RangTime isVisible={true} markedDates={null} startTime={this.pageParams.beginDate} endTime={this.pageParams.endDate} resultCall={this._resultCall} closeCall={() => { this.setState({ showTimeModal: false }) }} /> : null
        }

        {showSelect ? (<Common data={STATUS_LIST} itemFn={this.changeStatus} imgIndex={selectIndex} allClick={() => { this.setState({ showSelect: !this.state.showSelect }) }} styleOut={{ marginTop: 110 * scale }} type="selectModal" />) : null}

        {
          status != 'data' ? (<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />) : null
        }
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray,
  },
  tabWrap: {
    backgroundColor: '#0087FF',
    height: 58 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-around',
  },
  tabItem: {
    flexDirection: 'row',
    alignItems: 'center',
    height: 58 * scale,
  },
  tabValue: {
    fontSize: 14 * scale,
    color: '#FFFFFF',
    opacity: 0.6,
    marginRight: 8 * scale,
  },
  tabCount: {
    fontSize: 17 * scale,
    color: '#FFFFFF',
    opacity: 0.6,
  },
  selectedValue: {
    fontSize: 16 * scale,
    opacity: 1,
  },
  selectedCount: {
    fontSize: 20 * scale,
    opacity: 1,
  },
  filterWrap: {
    height: 56 * scale,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingLeft: 23 * scale,
    paddingRight: 23 * scale,
  },
  statusWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    height: 56 * scale,
  },
  statusBtn: {
    color: style.color.themeColor,
    marginRight: 10 * scale,
  },
  listWrap: {
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    height: '100%',
    paddingBottom: 116 * scale,
  },
  listItem: {
    backgroundColor: '#fff',
    borderRadius: 6 * scale,
    marginBottom: 20 * scale,
  },
  itemHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: 40 * scale,
    borderBottomWidth: 1 / PixelRatio.get(),
    borderStyle: 'solid',
    borderColor: '#E3E7F0',
  },
  itemBody: {
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    paddingBottom: 17 * scale,
    borderBottomWidth: 1 / PixelRatio.get(),
    borderStyle: 'solid',
    borderColor: '#E3E7F0',
  },
  itemFooter: {
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    paddingBottom: 20 * scale,
    paddingTop: 16 * scale,
  },
  tagIcon: {
    width: 22 * scale,
    height: 22 * scale,
    borderRadius: 11 * scale,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: -22 * scale
  },
  backoutIcon: {
    width: 20 * scale,
    height: 20 * scale,
    backgroundColor: '#CD4B4B',
    borderRadius: 20 * scale,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 8 * scale
  },
})